import { ref } from "vue";

export const useDraggable = () => {
  const content = ref<HTMLElement | null>(null); // 用于绑定拖拽的目标元素
  let isDragging = false;
  let offsetX = 0;
  let offsetY = 0;

  const startDrag = (e: MouseEvent) => {
    if (content.value) {
      isDragging = true;
      // 记录鼠标按下时的偏移量
      offsetX = e.clientX - content.value.offsetLeft;
      offsetY = e.clientY - content.value.offsetTop;
      // 添加鼠标移动和释放事件
      window.addEventListener("mousemove", drag);
      window.addEventListener("mouseup", stopDrag);
    }
  };

  const drag = (e: MouseEvent) => {
    if (isDragging && content.value) {
      // 根据鼠标位置调整内容的位置
      content.value.style.left = `${e.clientX - offsetX}px`;
      content.value.style.top = `${e.clientY - offsetY}px`;
    }
  };

  const stopDrag = () => {
    isDragging = false;
    // 移除鼠标移动和释放事件
    window.removeEventListener("mousemove", drag);
    window.removeEventListener("mouseup", stopDrag);
  };

  return {
    content,
    startDrag,
    stopDrag,
    drag
  };
};
